package com.example.demo.utils;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.ExpressionVisitorAdapter;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.StatementVisitorAdapter;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.select.SelectVisitorAdapter;

public class demo {
    public static void main(String[] args) throws JSQLParserException {
        // Define an Expression Visitor reacting on any Expression
// Overwrite the visit() methods for each Expression Class
        ExpressionVisitorAdapter<Void> expressionVisitorAdapter = new ExpressionVisitorAdapter<>() {
            public <S> Void visit(EqualsTo equalsTo, S context) {
                equalsTo.getLeftExpression().accept(this, context);
                equalsTo.getRightExpression().accept(this, context);
                return null;
            }
            public <S> Void visit(Column column, S context) {
                System.out.println("Found a Column " + column.getColumnName());
                return null;
            }
        };

// Define a Select Visitor reacting on a Plain Select invoking the Expression Visitor on the Where Clause
        SelectVisitorAdapter<Void> selectVisitorAdapter = new SelectVisitorAdapter<>() {
            @Override
            public <S> Void visit(PlainSelect plainSelect, S context) {
                return plainSelect.getWhere().accept(expressionVisitorAdapter, context);
            }
        };

// Define a Statement Visitor for dispatching the Statements
        StatementVisitorAdapter<Void> statementVisitor = new StatementVisitorAdapter<>() {
            public <S> Void visit(Select select, S context) {
                return select.getSelectBody().accept(selectVisitorAdapter, context);
            }
        };

        String sqlStr="select 1 from dual where a=b";
        Statement stmt = CCJSqlParserUtil.parse(sqlStr);

// Invoke the Statement Visitor without a context
        stmt.accept(statementVisitor, null);
    }
}
